package com.netty.web;

import com.netty.db.dao.entity.TableLamp;
import com.netty.db.service.TableLampService;
import com.netty.server.processor.down.DownCmdEnum;
import com.netty.server.processor.down.DownPlugin0X01;
import com.netty.server.sender.Callback;
import com.netty.server.sender.CmdRequest;
import com.netty.server.sender.CmdResponse;
import com.netty.server.sender.CmdSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @author: 王霄
 * @date: 2022/1/19 11:16
 **/
@RestController
@RequestMapping("/tableLamp")
public class CmdController {

    @Resource
    private CmdSender cmdSender;

    @Resource
    private TableLampService tableLampService;

    @GetMapping("/queryByMac")
    public TableLamp queryByMac(String mac) {
        return tableLampService.getById(mac);
    }

    /**
     * http://localhost:8082/tableLamp/set?mac=000000000001&switches=true&brightness=3
     * 01 00 01 02 03 04 01 00 06 00 00 00 00 00 01
     * \FF\01\00\00\00\00\00\00\00
     * \01\01\01\02\03\04\01\00\02\01\05
     */
    @GetMapping("/set")
    public Mono<String> setSwitch(@RequestParam String mac,
                                  @RequestParam boolean switches,
                                  @RequestParam byte brightness) {
        return Mono.create(monoSink -> {
            CmdRequest request = new CmdRequest();
            request.setCmd(DownCmdEnum.CMD_0X01);
            request.setMac(mac);
            request.setNeedAck(true);
            request.setTimeout(60000L);
            DownPlugin0X01 plugin = new DownPlugin0X01();
            plugin.setSwitches(switches);
            plugin.setBrightness(brightness);
            request.setData(plugin);
            request.setCallback(new Callback() {
                @Override
                public boolean onNext(CmdRequest req, CmdResponse resp) {
                    monoSink.success("设置成功");
                    return true;
                }

                @Override
                public void onTimeout(CmdRequest req) {
                    monoSink.success("设置失败，设备不在线");
                }
            });
            cmdSender.send(request);
        });
    }
}
